<template>
  <div class="allpage">
    <div class="addev-menu">活动信息</div>
    <el-form :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm addev-cont"
      v-if="ruleForm">
      <el-form-item label="团购标题："
        prop="GroupBuyTitle">
        <el-input v-model="ruleForm.GroupBuyTitle"
          placeholder="请输入团购标题"
          style="width: 50%"></el-input>
      </el-form-item>
      <el-form-item label="团购时间：">
        <el-date-picker type="datetime"
          v-model="GroupBuyStartTime"
          @change="getSTime"
          placeholder="选择日期"
          value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        <span>至</span>
        <el-date-picker type="datetime"
          v-model="GroupBuyEndTime"
          @change="getETimes"
          placeholder="选择日期"
          value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        <el-checkbox v-model="ruleForm.type"
          @change="checkbox(ruleForm.type)"
          label="长期"
          name="type"
          style="margin-left: 30px"></el-checkbox>
      </el-form-item>
      <el-form-item label="推荐返现："
        prop="choose">
        <el-radio-group v-model="ruleForm.choose"
          @change="agreeChange">
          <el-radio :label="1">开启</el-radio>
          <el-radio :label="2">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-select :disabled="selectStatus"
          v-model="ruleForm.region"
          placeholder=" 请选择推荐返现金额">
          <el-option v-for="(item, index) in options"
            :label="item.label"
            :key="index"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="团购详情设置:">
        <el-button @click="AddText">添加文字</el-button>
        <el-button @click="AddBImg">添加大图</el-button>
        <el-button @click="AddSImg">添加小图</el-button>
        <el-button @click="AddVideo">添加视频</el-button>
      </el-form-item>
      <!-- <el-row>
        <img :src="mainImg" width="100px" height="100px" alt="大图">
      </el-row>
      <el-row>
        <img :src="detailImg" width="100px" height="100px" alt="">
      </el-row> -->
      <draggable>
        <el-form-item v-for="(atitem, atindex) in addtext"
          :key="atindex"
          prop="textarea"
          class="box">
          <el-card :body-style="{ padding: '0px' }">
            <div class="box-f">
              <div class="box-f-t">
                <p>团购文字</p>
                <el-button type="primary"
                  icon="el-icon-delete"
                  class="mr"
                  @click="del1(atindex)">删除</el-button>
              </div>
              <div>
                <el-input type="textarea"
                  :rows="3"
                  placeholder="请输入文字信息"
                  v-model="textInfo[atindex]"></el-input>
              </div>
            </div>
          </el-card>
        </el-form-item>
        <el-form-item v-for="(abitem, abindex) in addbimg"
          :key="'info2-' + abindex"
          prop="GroupBuyBgImgUrl">
          <el-card :body-style="{ padding: '0px' }">
            <div class="box-f">
              <div class="box-f-t">
                <p>添加团购大图（一次只能添加一张）</p>
                <el-button @click="del2(abindex)"
                  type="primary"
                  icon="el-icon-delete"
                  class="mr">删除</el-button>
              </div>

              <el-upload action="http://gbtest.xiniuauto.com/api/Adm_System/UploadImgFile"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :limit="1"
                :file-list="bigUploadList[abindex]"
                :on-success="uploadSuccessbig"
                :on-remove="handleRemove"
                ref="mainImg">
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
          </el-card>
        </el-form-item>
        <el-form-item v-for="(asitem, asindex) in addsimg"
          :key="'info3-' + asindex">
          <el-card :body-style="{ padding: '0px' }">
            <div class="box-f">
              <div class="box-f-t">
                <p>添加团购小图（支持多张）</p>
                <el-button @click="del3(index)"
                  type="primary"
                  icon="el-icon-delete"
                  class="mr">删除</el-button>
              </div>
              <el-upload action="http://gbtest.xiniuauto.com/api/Adm_System/UploadImgFile"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :limit="9"
                :file-list="asindex===0?smallUploadImg:upLoadData"
                :on-success="uploadSuccessbySamll"
                :on-remove="removeSmallImg"
                ref="detailImg">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible"
                append-to-body>
                <img width="100%"
                  :src="dialogImageUrl"
                  alt />
              </el-dialog>
            </div>
          </el-card>
        </el-form-item>
        <el-form-item v-for="(avitem, avindex) in addvideo"
          :key="'info4-' + avindex">
          <el-card :body-style="{ padding: '0px' }">
            <div class="box-f">
              <div class="box-f-t">
                <p>添加团购视频（一次只能添加一个视频）</p>
                <el-button @click="del4(index)"
                  type="primary"
                  icon="el-icon-delete"
                  class="mr">删除</el-button>
              </div>
              <el-upload action="http://gbtest.xiniuauto.com/api/Adm_System/UploadImgFile"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :limit="1"
                :file-list="videoListData[avindex]"
                :on-success="uploadVideoSuccess"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>

              </el-upload>
              <el-dialog :visible.sync="dialogVisible"
                append-to-body>

                <video style="width:300px"
                  controls
                  autoplay
                  :src="videoListData[avindex]?videoListData[avindex][0]['url']:''"></video>
              </el-dialog>
            </div>
          </el-card>
        </el-form-item>
      </draggable>
      <!-- 编辑状态 显示input/bigImg/smallImg -->
      <!-- <div v-else style="width: 80%; margin-left: 10%">
        <div v-if="ruleForm.GroupBuyContentCode">
          <el-card v-if="
              ruleForm.GroupBuyContentCode[0].content !== '' &&
              ruleForm.GroupBuyContentCode[0].content
            " :body-style="{ padding: '10px' }" style="margin-bottom: 10px">
            <div class="box-f">
              <div class="box-f-t">
                <p>团购文字</p>
              </div>
              <div>
                <el-input type="textarea" :rows="3" placeholder="请输入文字信息"
                  v-model="ruleForm.GroupBuyContentCode[0].content"></el-input>
              </div>
            </div>
          </el-card>
        </div> -->

      <div style="width: 80%; margin-left: 10%">
        <!-- //渲染展示页面 -->

      </div>
    </el-form>
    <div class="addev-bottom">
      <el-button style="margin: 20px 0 10px 20px"
        @click="addgoods">添加商品</el-button>
      <div class="adden-menu table-style">
        <el-table class="addev-bottom-tab"
          :data="tableData"
          v-if="tableData"
          style="width: 100%">
          <el-table-column prop="ProductNumber"
            label="商品编号"></el-table-column>
          <el-table-column prop="ProductName"
            label="商品名称">
            <template slot-scope="scope">
              <p>{{ scope.row.ProductName }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="CurrentPrice"
            label="价格（元）">
            <template slot-scope="scope">
              <p>￥{{ scope.row.CurrentPrice }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="SoloProductModels"
            label="规格"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="del(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <botpage class="botpage-style"
        :currentPage="currentPage"
        :PageSize="PageSize"
        :total="total"
        @handleCurrentChange="currentChange"
        @handleSizeChange="pageSizeChange" />
    </div>
    <div class="btn"
      v-show="this.type == 'add'">
      <el-button @click="cancel">取消</el-button>
      <el-button @click="submitForm()">确定</el-button>
    </div>
    <div class="btn"
      v-show="this.type == 'edit'">
      <el-button @click="cancel">取消</el-button>
      <el-button @click="submitForm()">确定</el-button>
    </div>
    <add-dialog :dTitle="dialogTitle"
      :visible="dialogFormVisible"
      @closeDialog="close"
      :formData="form"
      @getNumber="getNumberData" />
  </div>
</template>

<script>
import Draggable from "vuedraggable";
import Botpage from "@/components/botpage/Botpage";
import AddDialog from "./AddDialog";
import {
  LoadGroupBuyProductList, //团购-> 小龙 -> 商品table内容
  LoadGroupBuyProductByNumber, //团购-> 小龙 -> form表单
  addGroupBuy,
  EditGroupBuyProductList, //添加form内容
  DeleteGroupBuyProductList, //删除table内容
  GetGBNumber, //获取团购码
} from "@/request/api";
export default {
  data () {
    return {
      dataNumber: "", //商品添加弹框获取的data
      msg: "",
      type: "",
      ProductNumber: "", //获取的Number
      index: "", //多个相同index for循环
      ruleForm: {
        type: false,
        choose: 1,
      },
      selectStatus: false, //select禁用
      GroupBuyStartTime: this.getNowTime(new Date()), //团购开始时间
      GroupBuyEndTime: this.getNowTime(new Date(+new Date() + 604800000)), //团购结束时间
      rules: {
        GroupBuyTitle: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 5, message: "活动名称长度不得少于 5 个字符", trigger: "blur" },
        ],
      },
      options: [
        //推荐返现
        { value: 1, label: "1元" },
        { value: 2, label: "2元" },
        { value: 3, label: "3元" },
      ],
      addtext: [], //文字
      addbimg: [], //大图
      addsimg: [], //小图
      addvideo: [], //video
      upLoadData: [], //上传图片数组
      dialogVisible: false,
      dialogImageUrl: "",
      tableData: [],
      currentPage: 1,
      PageSize: 10,
      total: 1,
      dialogFormVisible: false,
      dialogTitle: "", //弹框title
      form: {},
      // GBnumber: null,
      mainImg: "", //大图
      detailImg: [], //详情图
      videoSrc: "", //视频
      textInfo: [],
      picture: [],
      detailsMap: [],
      detailsIndex: 0,
      videos: [],
      detailText: [],
      detailBigImg: [],
      detailVideo: [],
      extract: [],
      /////大图的数据列表file-list
      bigUploadList: [],
      smallUploadImg: [],
      //小图详情图
      smallListData: [],
      videoListData: []

    };
  },
  created () {
    console.log(this.type);
    this.getInfo();
    this.getDetail();
    this.agreeChange();
  },
  methods: {
    //发送
    submitForm () {
      this.$refs["ruleForm"].validate((vali) => {
        if (vali) {
          this.ruleForm.GroupBuyStartTime = this.GroupBuyStartTime;
          this.ruleForm.GroupBuyEndTime = this.GroupBuyEndTime;
          this.ruleForm.GroupBuySalesMan =
            "0F743E61-2F5A-48CA-9F62-84CCC79F8865";
          console.log(this.ruleForm.GroupBuySalesMan);
          console.log(this.ruleForm.GroupBuyStartTime);
          console.log(this.ruleForm.GroupBuyEndTime);
          if (this.ruleForm.GBNumber == null) {
            this.ruleForm.GBNumber = this.$route.query.GBNumber;
            console.log(this.ruleForm.GBNumber);
          }
          console.log(this.ruleForm);
          //文字
          const text = this.textInfo.map((item) => {
            return { type: 'text', content: item }
          })
          //大图
          // this.ruleForm.GroupBuyContentCode[1] = []
          const maximg = this.picture.map((item) => {
            return { type: 'bigImg', src: item }
          })
          //视频
          const video = this.videos.map((item) => {
            return { type: 'video', src: item }
          })

          //小图
          let smallImg = [{
            type: 'smallImg',
            srcList: [...this.smallListData]
          }]

          let GroupBuyContentCode = [...text,...maximg,...video,...smallImg]
          this.ruleForm.GroupBuyContentCode = GroupBuyContentCode
          console.log(this.ruleForm)
          // debugger
          addGroupBuy(this.ruleForm).then((res) => {
            if (res.StatusCode === 200) {
              this.msg = res.Message;
              console.log(this.msg);
              this.$confirm("编辑团购活动成功!", "编辑团购活动成功", {});
              this.goback();
              console.log();
              // this.$parent.getTableData();
            }
          });
        }
      });
    },
    //详情table内容
    getInfo () {
      console.log(this.$route.query)
      this.type = this.$route.query.type;
      // console.log(this.type);
      this.ruleForm.GBNumber = this.$route.query.GBNumber
        ? this.$route.query.GBNumber
        : "";
      console.log(this.ruleForm.GBNumber);
      // if (this.ruleForm.GBNumber!= "") {
      LoadGroupBuyProductList({
        PageIndex: this.currentPage,
        PageSize: this.PageSize,
        OS: "PC",
        ScreenValues: this.ruleForm.GBNumber,
      })
        .then((res) => {
          this.tableData = res.Data;
          this.total = res.DataCounts;
          this.currentPage = res.PageIndexs;
          this.PageSize = res.PageCount;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //详情页面form内容
    getDetail () {
      LoadGroupBuyProductByNumber({
        GBNumber: this.ruleForm.GBNumber,
      })
        .then((res) => {
          if (this.$route.query.type != "add") {
            this.GroupBuyStartTime = res.Data.GroupBuyStartTime;
            this.GroupBuyEndTime = res.Data.GroupBuyEndTime;
          }
          this.ruleForm = res.Data;
          console.log(res.Data);
          if (!this.ruleForm.choose) {
            this.ruleForm.choose = 1;
          }
          if (res.Data.GroupBuyContentCode == null) {
            this.ruleForm.GroupBuyContentCode = [
              { type: "text", content: "" },
              { type: "bigImg", src: "" },
              { type: "smallImg", srcList: [] },
              { type: "video", src: "" },
            ];
          }
          const responseData = JSON.parse(res.Data.GroupBuyContentCode);
          this.detailText = responseData.filter(item => item.type === 'text')
          this.detailBigImg = responseData.filter(item => item.type === 'bigImg')
          this.detailVideo = responseData.filter(item => item.type === 'video')
          this.detailSmallImg = responseData.filter(item => item.type === 'smallImg')
          //普通文本
          this.detailText.forEach((item, i) => {
            this.textInfo[i] = item.content
            this.addtext.push(i)
          })
          //大图
          this.detailBigImg.forEach((item, i) => {
            this.addbimg.push(i)
            this.bigUploadList[i] = [{ name: 'bigIMg', url: item.src }]
            this.picture.push(item.src)
          })
          //小图详情图
          console.log();
          if (this.detailSmallImg[0].srcList.length !== 0) {
            this.addsimg.push(1)
            this.ruleForm.GroupBuyContentCode = JSON.parse(this.ruleForm.GroupBuyContentCode)
            this.detailSmallImg[0].srcList.forEach((item, i) => {
              this.smallUploadImg.push({ name: 'smallImg', url: item })
              this.smallListData.push(item)
            })
          }
          console.log(this.detailVideo);
          this.detailVideo.forEach((item, i) => {
            this.addvideo.push(i)
            this.videoListData[i] = [{ name: 'video', url: item.src }]
            this.videos.push(item.src)
          })
          //匹配中国汉字
          // const reg = /[\u4e00-\u9fa5]/g;

          // extract[0].content =
          //   extract[0] && extract[0].content.match(reg).join("");
          // this.ruleForm.GroupBuyContentCode = extract;
          // this.mainImg = extract[1].src;
          // this.detailImg = extract[2].srcList;
          // this.videoSrc = extract[3].src;
          // console.log(this.videoSrc);
          // }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //
    //table删除
    del (row) {
      this.$confirm("是否要删除该条信息?", "删除提示", {}).then((res) => {
        DeleteGroupBuyProductList({
          GBNumber: row.GBNumber,
          ProductNumber: row.ProductNumber,
        })
          .then((res) => {
            if (res.StatusCode === 200) {
              this.$confirm("该条信息删除成功！", "删除成功", {});
              this.getInfo();
            }
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
    //取消返回上一页
    cancel () {
      this.goback();
    },
    goback () {
      this.$router.back();
    },
    //监听获取
    getNumberData (msg) {
      console.log(msg + "接收页面-----------");
      this.dataNumber = msg;
      console.log(this.dataNumber);
    },
    //监听
    close (reload) {
      console.log(reload);
      this.dialogFormVisible = false;
    },
    //弹框
    addgoods () {
      this.dialogFormVisible = true;
      this.dialogTitle = "添加商品";
      this.form = this.ruleForm;
      if (this.form.GBNumber === null) {
        this.form.GBNumber = this.$route.query.GBNumber;
      }
    },
    //当前页面
    currentChange (event) {
      this.currentPage = event;
      this.getInfo();
    },
    //翻页
    pageSizeChange (event) {
      this.PageSize = event;
      this.getInfo();
    },
    //上传错误
    handleRemove (file) {

      console.log(1);
      console.log(file);
    },
    //删除小图方法
    removeSmallImg (file) {
      console.log(file);

      if (file.url.indexOf('blob') !== -1) {
        let url = file.response.OtherData + file.response.Data.DefaultUrl
        this.smallListData = this.smallListData.filter((item) => {
          return url !== item
        })

      } else {
        this.smallListData = this.smallListData.filter((item) => {
          return file.url !== item
        })
      }

      // this.ruleForm.GroupBuyContentCode
    },
    //上传主图地址
    uploadSuccessbig (response, file, fileList) {

      console.log(response);
      if (response.StatusCode === 200) {
        // this.ruleForm.GroupBuyContentCode[1].src =
        //   response.OtherData + response.Data.DefaultUrl;
        const mapStr = response.OtherData + response.Data.DefaultUrl
        this.picture.push(mapStr)
        this.bigUploadList.push = [{ name: 'bigIMg', url: response.OtherData + response.Data.DefaultUrl }]
      }
    },
    //详情图上传
    uploadSuccessbySamll (response, file, fileList) {
      console.log(response);
      console.log(this.addsimg)
      if (response.StatusCode === 200) {

        this.smallListData.push(response.OtherData + response.Data.DefaultUrl)
        console.log(this.smallListData);
      }
    },
    //视频上传
    uploadVideoSuccess (response, file, fileList) {
      console.log(response);
      if (response.StatusCode === 200) {
        // this.ruleForm.GroupBuyContentCode[3].src =
        //   response.OtherData + response.Data.DefaultUrl;
        const videoStr = response.OtherData + response.Data.DefaultUrl
        this.videos.push(videoStr)
      }
    },
    //上传图片
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //点击删除模态框
    del1 (index) {
      this.addtext.splice(index, 1);
      this.textInfo.splice(index, 1);
      console.log(this.textInfo);
    },
    del2 (index) {
      this.addbimg.splice(index, 1);
      this.picture.splice(index, 1);
      this.bigUploadList.splice(index, 1)
      console.log(index);
      console.log(this.picture);
    },
    del3 (index) {
      this.addsimg.splice(index, 1);
    },
    del4 (index) {
      this.addvideo.splice(index, 1);
      this.videos.splice(index, 1);
    },
    //点击添加模态框
    AddText () {
      console.log('1')
      this.addtext.push(1);
    },
    AddBImg () {
      console.log();
      this.addbimg.push(1);
    },
    AddSImg () {
      this.addsimg.push(0);
    },
    AddVideo () {
      this.addvideo.push(1);
      console.log(this.addvideo);

    },
    //时间
    getNowTime (datetime) {
      console.log(datetime)
      datetime.setDate(datetime.getDate());
      var year = datetime.getFullYear();
      var month = datetime.getMonth() + 1;
      var date = datetime.getDate();
      var hour = datetime.getHours();
      var f =
        datetime.getMinutes() < 10
          ? "0" + datetime.getMinutes()
          : datetime.getMinutes();
      var s =
        datetime.getSeconds() < 10
          ? "0" + datetime.getseconds()
          : datetime.getSeconds();
      month = month < 10 ? "0" + month : month;
      date = date < 10 ? "0" + date : date;
      hour = hour < 10 ? "0" + hour : hour;
      return year + "-" + month + "-" + date + " " + hour + ":" + f + ":" + s;
    },
    //时间开关
    checkbox (val) {
      if (val) {
        this.GroupBuyStartTime = new Date();
        this.GroupBuyEndTime = new Date(+new Date() + 31536000000);
      } else {
        this.ruleForm.type = false;
        this.GroupBuyStartTime = "";
        this.GroupBuyEndTime = "";
      }
    },
    //单选器
    agreeChange (val) {
      let that = this;
      that.selectStatus = val === "2" ? true : false;
    },
    //开始时间
    getSTime (val) {
      this.GroupBuyStartTime = val;
    },
    //结束时间
    getETimes (val) {
      this.GroupBuyEndTime = val;
    },
  },
  components: {
    Draggable,
    Botpage,
    AddDialog,
  },
};
</script>

<style lang="less" scoped>
.addev-menu {
  width: 98%;
  background-color: #f8f8f8;
  margin: 0 auto;
  height: 50px;
  line-height: 50px;
  font-weight: bold;
  padding-left: 20px;
  box-sizing: border-box;
}
.addev-cont {
  width: 90%;
  margin: 20px auto;
  .demo-ruleForm {
    width: 80%;
    margin: 0 auto;
  }
  .box-f {
    display: flex;
    flex-direction: column;
    flex: 1;
    .box-f-t {
      display: flex;
      justify-content: space-between;
    }
  }
}
.addev-bottom-tab {
  p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.btn {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>